<template>
  <div class="viewFile" id="nav-bar">
    <van-nav-bar
      :title="$route.meta.title"
      left-arrow
      @click-left="$router.go(-1)"
    />

    <div class="container">
      <div class="view_area">
        <img
          class="pdfimg"
          v-if="smallImageList"
          :src="smallImageList"
          @click="imagePreview([smallImageList])"
          alt=""
        />

        <div v-else-if="showSecondMenu">
          <div
            class="second_menus"
            v-for="(item, index) of tableData"
            :key="index"
          >
            <!-- 二级菜单,表格 -->
            <TableChoose
              :vcPrintTypeId="vcid"
              :ref="item.beforeId"
              :table="item"
              v-if="item.type === 'table'"
            ></TableChoose>
            <!-- 二级菜单,输入框 -->
            <InputMenu
              :vcPrintTypeId="vcid"
              :ref="item.beforeId"
              :table="item"
              v-else-if="item.type === 'input'"
            ></InputMenu>
            <!-- 二级菜单,单选 -->
            <Radio
              :vcPrintTypeId="vcid"
              :ref="item.beforeId"
              :table="item"
              v-else-if="item.type === 'radio'"
            ></Radio>
            <!-- 二级菜单,多选 -->
            <Checkout
              :vcPrintTypeId="vcid"
              :ref="item.beforeId"
              :table="item"
              v-else-if="item.type === 'checkbox'"
            ></Checkout>
          </div>
        </div>
      </div>
    </div>

    <!-- 非二级菜单 -->
    <footer class="footer" v-if="!showSecondMenu">
      <div class="left" @click="secondVerification('down')">下载PDF</div>
      <div class="right" @click="secondVerification('sendEmail')">发送邮箱</div>
    </footer>
    <!-- 二级菜单 -->
    <footer class="footer" v-else>
      <div class="right" @click="viewPic">查看预览图</div>
    </footer>

    <!-- 验证弹框 -->
    <van-popup
      v-model="showVer"
      round
      :close-on-click-overlay="false"
      closeable
    >
      <div class="ver_container">
        <p class="title" v-if="modes[current]">
          {{ $dictUtils.getDictLabel("svMode_map", modes[current].svType) }}
        </p>

        <van-swipe
          :autoplay="0"
          indicator-color="white"
          :loop="false"
          :show-indicators="false"
          @change="(index) => (current = index)"
        >
          <van-swipe-item v-for="(item, index) of modes" :key="index">
            <SmsCheck
              @submit="getProduction"
              v-if="item.svType === 'PHONE_CODE'"
              style="margin-top: 20px"
            ></SmsCheck>
            <FaceCheck v-if="item.svType === 'FACE'"></FaceCheck>
          </van-swipe-item>
        </van-swipe>
      </div>
    </van-popup>

    <!-- 选邮箱弹框 -->
    <Email ref="email" @submit="emailSubmit"></Email>
  </div>
</template>

<script>
import { ImagePreview } from "vant";
import TableChoose from "./components/tableChoose.vue";
import InputMenu from "./components/Input.vue";
import Radio from "./components/Radio.vue";
import Checkout from "./components/Checkout.vue";
import SmsCheck from "./components/SmsCheck.vue";
import FaceCheck from "./components/FaceCheck.vue";
import Email from "./components/Email.vue";
import { mapGetters } from "vuex";
export default {
  name: "previewFile",
  components: {
    Checkout,
    Radio,
    InputMenu,
    TableChoose,
    SmsCheck,
    FaceCheck,
    Email,
  },
  data() {
    return {
      fileProperty: "",
      smallImageList: "",
      vcid: "",
      pdfSerialId: "",
      tableData: [],
      pmtype: "",
      version: "",
      showVer: false, // 显示二次验证框框
      showSecondMenu: false,
      outerParams: {}, // 二级菜单多出来的获取预览图的参数
      modes: [], // 二次验证方式
      current: 0,
      modeForm: {
        svCode: "",
      },
      actionType: "",
      productInfo: {},
    };
  },
  created() {
    const { vcid, fileProperty } = this.$route.query;
    this.vcid = vcid;
    this.fileProperty = fileProperty;
    this.getSecondMenus();
  },
  computed: {
    ...mapGetters(["currentFile", "svModes"]),
  },
  methods: {
    // 邮箱生成订单
    emailSubmit(email) {
      this.operatingFile({ email });
    },
    // 发送邮箱 or 下载成绩单
    operatingFile({ email } = {}) {
      this.$toast.loading({ message: "加载中..." });
      const typeMap = {
        down: 2,
        sendEmail: 1,
      };
      const { vcid, fileProperty, pdfSerialId } = this;
      const { productNum, productId, productName } = this.productInfo;
      const data = {
        downloadType: typeMap[this.actionType],
        productNum,
        productId,
        fileName: productName,
        pdfSerialId,
        moduleType: Number(fileProperty) + 1,
        toEmail: email,
      };
      this.$http({
        url: "/private-xm/pay/downloadDoc",
        method: "post",
        data,
      })
        .then((res) => {
          this.$toast.clear();
          // 如果有数据就表示不是免费的
          if (res.data) {
            // 支付再这里做
            // this.orderInfo = res.data.shift();
            // if(this.$utils.Device("wechat")){
            //   this.payMoney()
            // }else{
            //   this.$toast('请在微信浏览器中使用支付功能')
            // }
          } else {
            this.$router.replace("/pageList/filePreview");
          }
        })
        .catch((error) => {
          this.$toast.clear();
          console.log(error, "error");
          this.$toast.fail(error);
        });
    },
    // 二次验证
    secondVerification(actionType) {
      this.actionType = actionType;
      const { currentFile, svModes } = this;
      // 1. 首先查这份文件是否需要验证
      if (currentFile.svEnable === "ON") {
        // 开
        // 2. 再查客户端的所有验证方式有几个是开启的, 得到 arr
        // 拿出来验证方式列表,过滤掉关闭的验证方式
        let modes = svModes.filter((v) => v.isEnable === "ON");
        // 3. 遍历 arr 由用户选择一项
        this.modes = modes;
        this.showVer = true;
      } else {
        // 不开
        this.getProduction();
      }
    },
    // 获取订单信息
    getProduction({ svMode, svCode } = {}) {
      this.$toast.loading({ message: "加载中..." });
      this.$http({
        url: "/private-xm/pay/getPayProductInfo",
        method: "post",
        data: {
          productNum: 1, // 数量,目前写死为1
          vcid: this.vcid,
          svMode,
          svCode,
        },
      })
        .then((res) => {
          this.$toast.clear();
          const productInfo = res.data[0];
          // 添加是否免费字段
          productInfo.isFree = productInfo.price > 0;
          // 处理商品价格
          let n = (productInfo.price / 100).toFixed(2);
          productInfo.price = n !== n ? 0 : n;
          this.productInfo = productInfo;
          if (this.actionType === "down") {
            this.operatingFile();
          } else if (this.actionType === "sendEmail") {
            this.$refs.email.init();
          }
          // this.$router.push(`/inlinePrint/sendemail?vcid=${this.vcid}&fileProperty=${this.fileProperty}&downloadType=1&pdfSerialId=${this.pdfSerialId}`)
        })
        .catch((error) => {
          this.$toast.clear();
          console.log(error, "error");
          this.$toast(error);
        });
    },
    // 获取二级菜单生成参数
    viewPic() {
      let outerParams = {};
      this.tableData.forEach((item) => {
        let refItem = this.$refs[item.beforeId];
        refItem &&
          this.$refs[item.beforeId].forEach((ref) => {
            outerParams = Object.assign(outerParams, ref.getParams());
          });
      });
      this.outerParams = outerParams;
      this.getViewPic();
    },
    // 获取预览图
    getViewPic() {
      this.$toast.loading({
        message: "生成预览图耗时较长,请耐心等待...",
      });
      this.$http({
        url: "/private-xm/electronicDocument/getPdfPic",
        method: "post",
        data: {
          fileProperty: this.vcid,
          ...this.outerParams,
        },
      })
        .then((res) => {
          this.$toast.clear();
          this.pdfSerialId = res.pdfSerialId;
          this.smallImageList = res.smallImageList;
          this.showSecondMenu = false;
        })
        .catch((error) => {
          console.log(error, "error");
          this.$toast.clear();
          // this.$toast(error);
          this.$dialog
            .alert({
              title: "提示",
              message: error,
            })
            .then(() => {
              this.$router.go(-1);
            });
        });
    },
    // 获取二级菜单
    getSecondMenus() {
      this.$toast.loading({
        message: "生成预览图耗时较长,请耐心等待...",
      });
      this.$http({
        url: "/private-xm/electronicDocument/pmType",
        method: "post",
        data: {
          fileProperty: this.vcid,
        },
      })
        .then(({ data, version }) => {
          this.$toast.clear();
          // 开发时测试代码
          // data = this.$cloneDeep(pmtypeJson.result.data);
          // version = this.$cloneDeep(pmtypeJson.version);
          if (!data || !data.length) {
            this.getViewPic();
            this.pmtype = 0;
          } else {
            data.forEach((item) => {
              item.beforeId = item.type + Math.random() + +new Date();
            });
            // 二级菜单数据
            this.tableData = data || [];
            // 菜单层级
            this.pmtype = 2;
            // 版本,目前没有分别
            this.version = version;
            this.showSecondMenu = true;
          }
        })
        .catch((error) => {
          this.$toast.clear();
          this.$toast(error);
          console.log(error, "error");
        });
    },
    imagePreview(urls) {
      ImagePreview(urls);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/variable.scss";
#nav-bar ::v-deep .van-nav-bar__title {
  // color: #fff;
  font-size: 0.506667rem /* 19/37.5 */;
}
.viewFile {
  padding: 0.266667rem /* 10/37.5 */;
  .ver_container {
    width: 90vw;
    min-height: 6.4rem /* 240/37.5 */;
    padding: 0.266667rem /* 10/37.5 */;
    .title {
      font-size: 0.426667rem + $fontsize /* 16/37.5 */;
      color: $primary;
      text-align: center;
    }
  }
  .footer {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    display: flex;
    padding: 0.266667rem /* 10/37.5 */;
    box-sizing: border-box;
    .left,
    .right {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0.453333rem /* 17/37.5 */;
      font-size: 0.293333rem + $fontsize /* 11/37.5 */;
      border-radius: 0.8rem /* 30/37.5 */;
    }
    .left {
      color: $primary;
      background: #fff;
      border: 1px solid #71bbff;
      color: #71bbff;
    }
    .right {
      background: linear-gradient(-90deg, #3fa1fc, #71bbff);
      color: #fff;
      margin-left: 0.266667rem /* 10/37.5 */;
    }
  }
  .container {
    padding: 0.346667rem /* 13/37.5 */;
    margin-bottom: 1.333333rem /* 50/37.5 */;
    .view_area {
      width: 100%;
      // 暂时放这里
      min-height: 10rem /* 375/37.5 */;
      box-shadow: 0 1px 3px 0 rgba(35, 24, 21, 0.11);
      overflow: hidden;
      border-radius: 0.213333rem /* 8/37.5 */;
      .second_menus {
        & > div {
          margin-bottom: 0.4rem /* 15/37.5 */;
        }
      }
      .pdfimg {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
